package com.pvdnc.riru.app;

import android.annotation.SuppressLint;
import android.app.Application;
import android.app.Instrumentation;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;

import com.pvdnc.riru.appinjector.HookEnvManager;
import com.pvdnc.riru.common.ApplicationObserverManager;

import java.lang.reflect.Method;
import java.util.List;

import andhook.lib.xposed.XC_MethodHook;
import andhook.lib.xposed.XposedBridge;

import static android.content.Context.CONTEXT_IGNORE_SECURITY;
import static android.content.Context.CONTEXT_INCLUDE_CODE;

@SuppressLint("PrivateApi")
public class HookApplications {
    private static final String TAG=HookApplications.class.getSimpleName();

    public static final HookApplications INSTANCE=new HookApplications();

    private HookApplications(){

    }

    public void hookAll(){
        try {
            hookCallApplicationOnCreate();

            HookEnvManager.INSTANCE.init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void hookCallApplicationOnCreate() throws Exception {
        Method method= Instrumentation.class.getDeclaredMethod("callApplicationOnCreate",
                Application.class);
        XposedBridge.hookMethod(method,new XC_MethodHook(){
            @Override
            protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                super.beforeHookedMethod(param);
                try {
                    Application app = (Application) param.args[0];
                    String pkgName = app.getPackageName();
                    Log.d(TAG, "before calling Application.onCreate for pkg:" + pkgName);
                    ApplicationObserverManager.INSTANCE.callObserver(app);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        Log.d(TAG,"finish hooking callApplicationOnCreate");
    }
}
